package com.gitee.deeround.demo.util;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author wanghao 913351190@qq.com
 * @create 2022/3/17 10:35
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    static ApplicationContext context;
    static DefaultListableBeanFactory defaultListableBeanFactory;

    public static ApplicationContext getContext() {
        return context;
    }

    public static void registerBean(String beanName, Object obj) {
        if (defaultListableBeanFactory == null) {
            defaultListableBeanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
        }
        defaultListableBeanFactory.setAllowBeanDefinitionOverriding(true);
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(obj.getClass());
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
    }

    public static void removeBean(String beanName) {
        if (defaultListableBeanFactory == null) {
            defaultListableBeanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
        }
        try {
            defaultListableBeanFactory.removeBeanDefinition(beanName);
        } catch (Exception e) {
            //ignore
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContextUtils.context = context;
    }

}
